package com.twu.biblioteca.controllers;

import com.twu.biblioteca.helpers.Table;
import com.twu.biblioteca.models.Book;
import com.twu.biblioteca.models.BookDAO;

import java.util.ArrayList;
import java.util.List;

public final class ConsoleListBook extends Console {

    @Override
    public void run() {
        BookDAO bookDAO = new BookDAO();

        List<Book> books = bookDAO.getBooksWithoutCheckout();

        int charsId = 2;
        int charsName = 4;
        int charsAuthor =  6;
        int charsYearPublished = 14;

        for (Book book : books){
            int lengthId = Long.toHexString(book.getId()).length();
            int lengthName = book.getName().length();
            int lengthAuthor = book.getAuthor().length();
            int lengthYearPublished = book.getYearPublished().toString().length();

            if (lengthId > charsId){
                charsId = lengthId;
            }
            if(lengthName > charsName){
                charsName = lengthName;
            }
            if(lengthAuthor > charsAuthor){
                charsAuthor = lengthAuthor;
            }
            if (lengthYearPublished > charsYearPublished){
                charsYearPublished = lengthYearPublished;
            }
        }

        charsId += 2;
        charsName += 2;
        charsAuthor += 2;
        charsYearPublished += 2;

        Table table = new Table();

        ArrayList<Integer> limits = new ArrayList<Integer>();
        limits.add(charsId);
        limits.add(charsName);
        limits.add(charsAuthor);
        limits.add(charsYearPublished);
        table.setLimits(limits);

        ArrayList<String> headers = new ArrayList<String>();
        headers.add("Id");
        headers.add("Name");
        headers.add("Author");
        headers.add("Year Published");
        table.addData(headers);

        table.addDiv();

        ArrayList<String> details = new ArrayList<String>();

        for (Book book : books){
            details.add(Long.toHexString(book.getId()));
            details.add(book.getName());
            details.add(book.getAuthor());
            details.add(book.getYearPublished().toString());

            table.addData(details);

            details.removeAll(details);
        }

        this.io.getOutput().append("\n\n" + table.getTable() + "\n\n");

        new ConsoleMainMenu().run();

    }
}